/**
 * 工作项管理页面
 */

'use client';

import React, { useState, useCallback, useEffect } from 'react';
import Link from 'next/link';
import {
  Layout,
  Space,
  Button,
  message,
  Card,
  Statistic,
  Row,
  Col,
  Typography,
} from 'antd';
import {
  PlusOutlined,
  DownloadOutlined,
  ReloadOutlined,
  BugOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  ProjectOutlined,
} from '@ant-design/icons';
import WorkItemQueryForm from '../../components/WorkItemQueryForm';
import WorkItemTable from '../../components/WorkItemTable';
import WorkItemDetailModal from '../../components/WorkItemDetailModal';
import { useWorkItems } from '../../hooks/useWorkItems';
import { pingCodeAPI } from '../../utils/pingcodeApi';
import type { WorkItem, WorkItemQueryParams } from '../../types/workItem';

const { Content } = Layout;
const { Title } = Typography;

export default function WorkItemManagePage() {
  const [queryParams, setQueryParams] = useState<WorkItemQueryParams>({});
  const [selectedWorkItem, setSelectedWorkItem] = useState<WorkItem | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [allWorkItemsForFilter, setAllWorkItemsForFilter] = useState<WorkItem[]>([]); // 存储用于筛选的所有工作项
  
  const { workItems, loading, total, fetchWorkItems } = useWorkItems();

  // 页面加载时不自动加载数据，等待用户选择查询条件
  // useEffect(() => {
  //   fetchWorkItems({ page_size: 20 });
  // }, [fetchWorkItems]);

  // 处理查询
  const handleSearch = useCallback((params: WorkItemQueryParams) => {
    setQueryParams(params);
    // 重置到第一页
    const searchParams = { ...params, page_index: 1 };
    fetchWorkItems(searchParams);
    
    // 获取用于筛选的所有工作项
    fetchAllWorkItemsForFilter(params);
  }, [fetchWorkItems]);

  // 获取用于筛选的所有工作项
  const fetchAllWorkItemsForFilter = useCallback(async (params: WorkItemQueryParams) => {
    // 如果没有查询条件，不获取所有数据
    if (!params || Object.keys(params).length === 0) {
      setAllWorkItemsForFilter([]);
      return;
    }
    
    try {
      // 创建一个不包含分页参数的查询参数对象
      const filterParams: WorkItemQueryParams = {};
      Object.keys(params).forEach(key => {
        if (key !== 'page_index' && key !== 'page_size') {
          filterParams[key as keyof WorkItemQueryParams] = params[key as keyof WorkItemQueryParams];
        }
      });
      
      // 设置合理的页面大小以获取更多数据，但要遵守API限制
      filterParams.page_size = 100; // 遵守API限制(1-100)
      
      const response = await pingCodeAPI.getWorkItems(filterParams);
      setAllWorkItemsForFilter(response.values || []);
    } catch (error) {
      console.error('获取筛选数据失败:', error);
      setAllWorkItemsForFilter([]);
    }
  }, []);

  // 处理分页变化
  const handlePageChange = useCallback((page: number, pageSize: number) => {
    const newParams = { 
      ...queryParams, 
      page_index: page, 
      page_size: pageSize 
    };
    setQueryParams(newParams);
    fetchWorkItems(newParams);
  }, [queryParams, fetchWorkItems]);

  // 查看工作项详情
  const handleViewWorkItem = (workItem: WorkItem) => {
    setSelectedWorkItem(workItem);
    setDetailModalVisible(true);
  };

  // 编辑工作项
  const handleEditWorkItem = (workItem: WorkItem) => {
    message.info(`编辑工作项: ${workItem.title}`);
    // TODO: 实现编辑功能
  };

  // 删除工作项
  const handleDeleteWorkItem = (workItem: WorkItem) => {
    message.success(`删除工作项: ${workItem.title}`);
    // TODO: 实现删除功能，然后刷新列表
    fetchWorkItems(queryParams);
  };

  // 导出工作项
  const handleExportWorkItems = (items: WorkItem[]) => {
    const exportData = items.map(item => ({
      编号: item.identifier,
      标题: item.title,
      类型: item.type,
      状态: item.state.name,
      优先级: item.priority?.name || '',
      负责人: item.assignee?.display_name || '',
      项目: item.project.name,
      故事点: item.story_points || '',
      预估工时: item.estimated_workload || '',
      剩余工时: item.remaining_workload || '',
      开始时间: item.start_at ? new Date(item.start_at * 1000).toISOString().split('T')[0] : '',
      结束时间: item.end_at ? new Date(item.end_at * 1000).toISOString().split('T')[0] : '',
      创建时间: new Date(item.created_at * 1000).toISOString().split('T')[0],
      描述: item.description || '',
    }));

    // 创建 CSV 内容
    const headers = Object.keys(exportData[0] || {});
    const csvContent = [
      headers.join(','),
      ...exportData.map(row => 
        headers.map(header => {
          const value = row[header as keyof typeof row];
          return `"${String(value).replace(/"/g, '""')}"`;
        }).join(',')
      )
    ].join('\n');

    // 下载文件
    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `工作项导出_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    message.success(`成功导出 ${items.length} 条工作项数据`);
  };

  // 刷新数据
  const handleRefresh = () => {
    console.log('手动刷新数据，当前查询参数:', queryParams);
    fetchWorkItems(queryParams);
  };

  // 测试API连接
  const handleTestApi = async () => {
    console.log('开始测试API连接');
    try {
      // 先测试获取项目列表
      const projects = await pingCodeAPI.getProjects({ page_size: 5 });
      console.log('获取项目列表成功:', projects);
      message.success(`成功获取到 ${projects.values?.length || 0} 个项目`);
      
      // 如果有项目，尝试获取第一个项目的工作项
      if (projects.values && projects.values.length > 0) {
        const firstProject = projects.values[0];
        const workItems = await pingCodeAPI.getWorkItems({ 
          project_id: firstProject.id, 
          page_size: 5 
        });
        console.log('获取工作项成功:', workItems);
        message.success(`项目 "${firstProject.name}" 有 ${workItems.values?.length || 0} 个工作项`);
      }
    } catch (error) {
      console.error('API测试失败:', error);
      message.error(`API测试失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };

  // 计算统计数据
  const getStatistics = () => {
    const stats = {
      total: total || workItems.length, // 使用服务端返回的总数
      bug: 0,
      completed: 0,
      inProgress: 0,
      pending: 0,
    };

    workItems.forEach((item: WorkItem) => {
      if (item.type === 'bug') stats.bug++;
      
      switch (item.state.type) {
        case 'completed':
          stats.completed++;
          break;
        case 'in_progress':
          stats.inProgress++;
          break;
        case 'pending':
          stats.pending++;
          break;
      }
    });

    return stats;
  };

  const statistics = getStatistics();

  return (
    <Layout className="min-h-screen bg-gray-50">
      <Content className="p-6">
        <div className="max-w-full mx-auto space-y-6">
          {/* 页面标题和操作按钮 */}
          <div className="flex justify-between items-center">
            <div>
              <Title level={2} className="!mb-0">
                工作项管理
              </Title>
              <div className="text-sm text-gray-500 mt-1">
                API URL: {process.env.NEXT_PUBLIC_PINGCODE_API_URL || '未配置'} | 
                Token: {process.env.NEXT_PUBLIC_PINGCODE_ACCESS_TOKEN ? 
                  `${process.env.NEXT_PUBLIC_PINGCODE_ACCESS_TOKEN.substring(0, 8)}...` : '未配置'}
              </div>
            </div>
            <Space>
              <Link href="/projects">
                <Button icon={<ProjectOutlined />}>
                  项目管理
                </Button>
              </Link>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => message.info('创建工作项功能待实现')}
              >
                创建工作项
              </Button>
              <Button
                icon={<ReloadOutlined />}
                onClick={handleRefresh}
                loading={loading}
              >
                刷新
              </Button>
              <Button
                onClick={handleTestApi}
                type="dashed"
              >
                测试API
              </Button>
            </Space>
          </div>

          {/* 统计信息 */}
          <div style={{ 
            padding: '8px 0', 
            borderBottom: '1px solid #f0f0f0', 
            marginBottom: '16px',
            fontSize: '14px',
            color: '#666'
          }}>
            <Space size={24}>
              <span>
                <CheckCircleOutlined style={{ color: '#1890ff', marginRight: 4 }} />
                总数: <strong style={{ color: '#1890ff' }}>{statistics.total}</strong>
              </span>
              <span>
                <BugOutlined style={{ color: '#ff4d4f', marginRight: 4 }} />
                缺陷: <strong style={{ color: '#ff4d4f' }}>{statistics.bug}</strong>
              </span>
              <span>
                <ClockCircleOutlined style={{ color: '#faad14', marginRight: 4 }} />
                进行中: <strong style={{ color: '#faad14' }}>{statistics.inProgress}</strong>
              </span>
              <span>
                <CheckCircleOutlined style={{ color: '#52c41a', marginRight: 4 }} />
                已完成: <strong style={{ color: '#52c41a' }}>{statistics.completed}</strong>
              </span>
            </Space>
          </div>

          {/* 用户提示卡片 */}
          {workItems.length === 0 && !loading && (
            <Card className="bg-blue-50 border-blue-200">
              <div className="text-center py-4">
                <div className="text-lg font-semibold text-blue-800 mb-2">
                  🚀 欢迎使用工作项管理系统
                </div>
                <div className="text-blue-600 mb-4">
                  请在下方查询表单中选择项目来查看工作项，或点击“测试API”按钮验证连接是否正常。
                </div>
                <Space>
                  <Button type="primary" onClick={handleTestApi}>
                    测试API连接
                  </Button>
                  <Button onClick={handleRefresh}>
                    刷新数据
                  </Button>
                </Space>
              </div>
            </Card>
          )}

          {/* 查询表单 */}
          <WorkItemQueryForm
            onSearch={handleSearch}
            loading={loading}
            initialValues={queryParams}
          />

          {/* 工作项表格 */}
          <Card 
            title={`工作项列表 (第${queryParams.page_index || 1}页，共${workItems.length}条，总计: ${total || 0})`}
            extra={
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExportWorkItems(workItems)}
                disabled={workItems.length === 0}
              >
                导出当前页
              </Button>
            }
            styles={{ body: { padding: 0 } }}
          >
            <WorkItemTable
              workItems={workItems}
              allWorkItems={allWorkItemsForFilter}
              loading={loading}
              total={total}
              currentPage={queryParams.page_index || 1}
              pageSize={queryParams.page_size || 100}
              onView={handleViewWorkItem}
              onEdit={handleEditWorkItem}
              onDelete={handleDeleteWorkItem}
              onExport={handleExportWorkItems}
              onPageChange={handlePageChange}
              projectId={queryParams.project_id}
            />
          </Card>

          {/* 工作项详情模态框 */}
          <WorkItemDetailModal
            workItem={selectedWorkItem}
            visible={detailModalVisible}
            onClose={() => {
              setDetailModalVisible(false);
              setSelectedWorkItem(null);
            }}
          />
        </div>
      </Content>
    </Layout>
  );
}